import { fetchFilmDetail } from '../../comm/script/fetch.js'

const app = getApp()

Page({
    data: {
        film: {},
        showLoading: true,
        options: null,
        rating: 0,
        averageRating: 0,
        isRating: false
    },

    onLoad: function (options) {
        this.setData({ 
            options
        })
        this.loadFilmDetail(options.id, options.type)
        this.loadRatings(options.id)
    },

    async loadRatings(filmId) {
        try {
            const userId = wx.getStorageSync('userId') || 'anonymous'
            
            // 使用模拟数据
            const mockUserRating = { rating: 0 }
            const mockAverageRating = { average: 4.5 }

            this.setData({
                rating: mockUserRating.rating,
                averageRating: mockAverageRating.average
            })
        } catch (error) {
            console.error('加载评分失败:', error)
            wx.showToast({
                title: '加载评分失败',
                icon: 'none'
            })
        }
    },

    loadFilmDetail: function (id, type) {
        wx.showLoading({
            title: '加载中...'
        })
        fetchFilmDetail.call(this, `/v2/movie/subject/${id}`, id, {
            success: (res) => {
                // 字段适配逻辑开始
                let adapted = {};
                if (type === 'coming_soon') {
                    adapted = {
                        id: res.id,
                        title: res.title,
                        original_title: res.originalTitle || res.original_title || '',
                        images: { large: res.imageUrl || res.image_url || '' },
                        year: (res.releaseDate || res.release_date || '').toString().slice(0, 4),
                        directors: res.director ? res.director.split(',').map((name, idx) => ({ id: idx + '', name: name.trim(), avatars: { small: '' } })) : [],
                        casts: res.cast ? res.cast.split(',').map((name, idx) => ({ id: idx + '', name: name.trim(), avatars: { small: '' } })) : [],
                        genres: res.genres ? res.genres.split(',') : [],
                        summary: res.description || '',
                        wish_count: res.wishCount || res.wish_count || 0,
                        ratings_count: 0,
                        rating: { average: 0 },
                        durations: res.duration ? [res.duration] : [],
                        countries: [],
                        languages: [],
                        pubdate: res.releaseDate || res.release_date || ''
                    };
                } else {
                    adapted = {
                        id: res.id,
                        title: res.title,
                        original_title: res.originalTitle || res.original_title || '',
                        images: { large: res.imageUrl || res.image_url || (res.images ? res.images.large : '') },
                        year: (res.releaseDate || res.release_date || '').toString().slice(0, 4),
                        directors: res.director ? res.director.split(',').map((name, idx) => ({ id: idx + '', name: name.trim(), avatars: { small: '' } })) : (res.directors || []),
                        casts: res.cast ? res.cast.split(',').map((name, idx) => ({ id: idx + '', name: name.trim(), avatars: { small: '' } })) : (res.casts || []),
                        genres: res.genres ? (Array.isArray(res.genres) ? res.genres : res.genres.split(',')) : [],
                        summary: res.summary || '',
                        wish_count: res.wishCount || res.wish_count || 0,
                        ratings_count: res.ratings_count || 0,
                        rating: res.rating || { average: 0 },
                        durations: res.durations || (res.duration ? [res.duration] : []),
                        countries: res.countries || [],
                        languages: res.languages || [],
                        pubdate: res.releaseDate || res.release_date || ''
                    };
                }
                this.setData({
                    film: adapted,
                    showLoading: false
                })
                wx.hideLoading()
                console.log('loadFilmDetail - showLoading is now:', this.data.showLoading)
            },
            fail: (err) => {
                console.error('获取电影详情失败:', err)
                wx.hideLoading()
                wx.showToast({
                    title: '获取电影详情失败',
                    icon: 'none',
                    duration: 2000
                })
            }
        }, type)
    },

    async rateFilm(e) {
        const rating = e.currentTarget.dataset.rating
        const filmId = this.data.options.id
        const userId = wx.getStorageSync('userId') || 'anonymous'

        this.setData({ isRating: true })

        try {
            // 使用模拟数据
            this.setData({
                rating: rating,
                averageRating: (this.data.averageRating + rating) / 2
            })
            
            wx.showToast({
                title: '评分成功',
                icon: 'success',
                duration: 2000
            })
        } catch (error) {
            console.error('评分失败:', error)
            wx.showToast({
                title: '评分失败，请重试',
                icon: 'none',
                duration: 2000
            })
        } finally {
            this.setData({ isRating: false })
        }
    },

    goBack: function() {
        wx.navigateBack()
    },

    viewPersonDetail: function(e) {
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/personDetail/personDetail?id=${id}`
        })
    },

    viewFilmByTag: function(e) {
        const tag = e.currentTarget.dataset.tag
        wx.navigateTo({
            url: `/pages/searchResult/searchResult?tag=${tag}`
        })
    },

    previewImg: function(e) {
        const src = e.currentTarget.dataset.src
        wx.previewImage({
            current: src,
            urls: [src]
        })
    }
})